package com.cb.admin.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cb.auth.AuthRealm;
import com.cb.auth.ShiroSessionListener;
import com.cb.util.JSONUtil;

/**
 * 
 * @author Administrator
 * 页面
 */
@Controller
public class HomeController extends BaseController{
	
	@Autowired
	private ShiroSessionListener shiroSessionListener;

    @RequestMapping("/")
    public String index(HttpSession session,Model model) {
    	System.out.println("-----"+returnSessionObj(session));
    	System.out.println("--SessionCount--"+shiroSessionListener.getSessionCount());
    	model.addAttribute("userInfor",returnSessionObj(session));
        return "main";
    }
    
    //访问login时跳到login.jsp
    @RequestMapping("/login")
    public String login() {
        return "login";
    }
    
    /**
     * 登录方法
     * @param account
     * @param pwd
     * @param session
     * @return
     */
    //用户登录
    @RequestMapping(path = "/loginUser", method = RequestMethod.POST)
    public String loginUser(@RequestParam("account") String account, @RequestParam("pwd") String pwd, 
    						@RequestParam("captcha")String captcha, HttpSession session,Model model,
    						HttpServletRequest request) {
    	
    	//校验验证码
        //session中的验证码
        String sessionCaptcha = (String) SecurityUtils.getSubject().getSession().getAttribute(CaptchaController.KEY_CAPTCHA);
        if (null == captcha || !captcha.equalsIgnoreCase(sessionCaptcha)) {
            model.addAttribute("msg","验证码错误！");
            return "login";
        }
    	
        //把前端输入的username和password封装为token
    	//第一步：收集用户身份和证明
        UsernamePasswordToken token = new UsernamePasswordToken(account, pwd,true);
        //第二步：提交身份和证明
        Subject subject = SecurityUtils.getSubject();
        try {
        	//三步：处理成功或失败
            subject.login(token);
//            session.setAttribute("user", subject.getPrincipal());
            return "redirect:/";
        } catch (Exception e) {
        	String exception = (String)request.getAttribute("shiroLoginFailure");
        	if(e instanceof UnknownAccountException){
        		model.addAttribute("msg", "帐号密码错误！或账号不存在！");
        	}
        	if(e instanceof IncorrectCredentialsException){
        		model.addAttribute("msg", "帐号密码错误！");
        	}
        	if(e instanceof LockedAccountException){
        		model.addAttribute("msg", "帐号被锁定请联系管理员！");
        	}
            return "login";
        }
    }
    
    /**
     * 跳转到无权限页面
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/unauthorized")
    public String unauthorized(HttpSession session, Model model) {
        return "unauthorized";
    }
    
    /**
     * 给用户刷新权限
     * @param model
     * @return
     */
    @RequestMapping("reloadPermission")
    @ResponseBody
    public String reloadPermission(Model model) {

        //添加成功之后 清除缓存
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager)SecurityUtils.getSecurityManager();
        AuthRealm shiroRealm = (AuthRealm) securityManager.getRealms().iterator().next();
        //清除权限 相关的缓存
        shiroRealm.clearAllCache();
        
        return JSONUtil.returnSuccessResult("给用户刷新权限成功");
    }

    //错误返回json
//    @RequestMapping("/json")
//    public String json() throws MyException {
//        throw new MyException("发生错误2");
//    }

    //错误返回页面
//    @RequestMapping("/mainPage")
//    public String mainPage() throws Exception {
//        throw new Exception("发生错误");
//    }
}